#
# pgy文件上传脚本
# cmd: python3 helper4PgyUpload.py --BuildType=test --FilePath=/Users/guodong/workspace1/guang-app/build/app/outputs/flutter-apk/app-ci-release.apk
# desc: 上传文件到pgy，然后下载pgy二维码到apk/ipa同目录下， 生成.qrcode.png & .uploadRsp.json
import os
import json
import string
import sys
import time
import getopt
import helperUtils as Utils

try:
    import requests
except ImportError:
    os.system("pip3 install requests")
    os.system("pip3 install requests-toolbelt")
    import requests
else:
    pass

_TAG = "helper4PgyUpload"

Utils.log(_TAG, "build argv:" + str(sys.argv))

BuildType = ""
FilePath = ""

try:
    opts, args = getopt.getopt(sys.argv[1:], "hu:p:", ["help", "FilePath=", "BuildType="])
except getopt.GetoptError:
    sys.exit(2)
for opt, arg in opts:
    if opt in ("-h", "--help"):
        sys.exit()
    elif opt in ("--BuildType"):
        BuildType = arg
    elif opt in ("--FilePath"):
        FilePath = arg

Utils.log(_TAG, "BuildType:" + BuildType + " FilePath:" + FilePath)

pgyUploadApikey = "6ae37836d99997417a940a924d432c4f"
if BuildType == "pub":
    pgyUploadApikey = "be8580dcf19c15fc46166aee6ff52326"
elif BuildType == "test":
    pgyUploadApikey = "6ae37836d99997417a940a924d432c4f"


def downloadPgyQrcode(img_url: string, build_version: string):
    Utils.log(_TAG, "download pgyer qrcode image...")

    Utils.log(_TAG, "FilePath ------?" +FilePath)
    Utils.log(_TAG, "FilePath ------?" +FilePath)
    Utils.log(_TAG, "FilePath ------?" +FilePath)
    exit = os.path.isfile(FilePath)
    if not exit:
        Utils.log(_TAG, "file not exist")
        return None
    r = requests.get(img_url)
    qrcodeFilePath = FilePath + ".qrcode.png"
    with open(qrcodeFilePath, 'wb') as f:
        f.write(r.content)
    pass


def uploadFileAndDownloadQrcode():
    exit = os.path.isfile(FilePath)
    if not exit:
        Utils.log(_TAG, "file not exist")
        return None
    Utils.log(_TAG, "start upload:" + FilePath)
    uploadBgnTime = time.time()
    uploadurl = "https://www.xcxwo.com/apiv2/app/upload"
    res = requests.post(url=uploadurl, files={"file": open(
        FilePath, 'rb')},
                        data={"_api_key": pgyUploadApikey, "buildUpdateDescription": Utils.last20GitSubmit()})

    Utils.log(_TAG, "Response:")
    Utils.log(_TAG, res.content)
    jsonObj = json.loads(res.content)
    uploadRspFilePath = FilePath + ".uploadRsp.json";
    with open(uploadRspFilePath, 'wb') as f:
        f.write(res.content)
    code = jsonObj["code"]
    if code == 0:
        data = jsonObj['data']
        buildQRCodeURL = data['buildQRCodeURL']
        buildBuildVersion = data['buildBuildVersion']
        Utils.log(_TAG, "buildQRCodeURL: " + buildQRCodeURL + " buildBuildVersion:" + buildBuildVersion
                  + " Upload done cost(" + str(int(time.time() - uploadBgnTime)) + "s)")
        downloadBgnTime = time.time()
        downloadPgyQrcode(buildQRCodeURL, buildBuildVersion)
        Utils.log(_TAG, "Download PgyQrcode done, cost(" + str(int(time.time() - downloadBgnTime)) + "s)")
    else:
        Utils.log(_TAG, "pgyer upload error")
        return None
    pass


uploadFileAndDownloadQrcode()
